# _*_coding     : UTF_8_*_
# Author        :Jie Shen
# CreatTime     :2022/1/3 9:28
import pandas as pd


def get_enterprises_num(data_source_csv, test_csv):
    """
    若city为null
    :param data_source_csv:
    :param test_csv:
    :return:
    """
    try:
        data_source_df = pd.read_csv(data_source_csv, encoding="gbk")
    except:
        data_source_df = pd.read_csv(data_source_csv)


    try:
        _csv = pd.read_csv(test_csv, encoding="gbk")
    except:
        _csv = pd.read_csv(test_csv)

    for i in range(_csv.shape[0]):
        # 0 是index
        district = _csv.iloc[i, 1]
        province_city = _csv.iloc[i, 2]

        # 由于省和市拼在一起
        # 省和市的字符串长度至少大于2
        split_line = 2
        while True:
            # 分割线越界，返回
            if split_line == len(province_city) - 1:
                num = is_exist(data_source_df, province_city, district)
                break
            province = province_city[:split_line:]
            city = province_city[split_line::]
            num = is_exist(data_source_df, province, city, district)
            if num is not None:
                break
            # 若city不存在，那么district变为city
            split_line += 1

        _csv.iloc[i, 3] = num
    _csv.columns = ["", "区", "省市", "高新企业数"]
    _csv.to_csv("result.csv", encoding="gbk", index=False)


def is_exist(data_source_df, province, city, district=None):
    """
    在源文件中查找province, city, district是否存在
        * 若存在，返回对应的高新企业数；
        * 若不存在,return None
    :param data_source_df: 数据源的pandas对象
    :param province:
    :param city:
    :param district:
    :return:
    """
    df = data_source_df
    size = df.shape[0]
    for i in range(size):
        p = df.iloc[i, 0]
        c = df.iloc[i, 1]
        d = df.iloc[i, 2]
        num = df.iloc[i, 3]

        # 省不匹配，跳过
        if province not in p:
            continue

        # 市不匹配，跳过
        if city not in c:
            continue
        # 区匹配
        # 两者都有区
        if not pd.isnull(district) and not pd.isnull(d):
            if district in d:
                return num
        # 两者都没有区
        if pd.isnull(district) and pd.isnull(d):
            return num

    return None


if __name__ == '__main__':
    test_csv = "test.csv"
    filename = "out.csv"
    # df = pd.read_csv(filename, encoding="gbk")
    # df.to_csv("test.csv")
    # 浙江省,杭州市,临平区,115.0
    # 北京市,东城区,,807.0
    get_enterprises_num(filename, test_csv)
    # num = is_exist(df, "北京", "东城")
    # print(num)
    # get_enterprises_num(filename, test_csv)
